# reads an external text file, csv and turns it into an xml file.

# csv file format:
# name,lastname,age,state

#xml file format:
# <persons>
#   <person>
#       <name></name>
#       <lastname></lastname>
#       <age></age>
#       <state></state>
#   </person>
# </persons>
#

# import elements
import os.path
from xml.etree import ElementTree as ET

# global variables
FILE = "personsCsv.csv"
XML_FILE = "personsXml.xml"

# first name list
first_names = [
    'Monica'
    , 'Maria'
    , 'Gustavo'
    , 'Pietra'
    , 'Carlos'
]

# last name list
last_names = [
    'Silva'
    , 'DePaula'
    , 'Heisenberg'
    , 'Bonfim'
]

# ages list
ages = [25,32,5,14,78]

# states list
states = ['WA','AZ','FL','NY']

# generates a list of persons
def generateContent():
    content = []
    for fn in first_names:
        for la in last_names:
            for a in ages:
                for s in states:
                    person = fn, la, str(a), s
                    content.append(person)
    return content


# main program
# reads a file
fileExist = os.path.isfile(FILE)
if fileExist:
    csvFile = open(FILE, "r")
else:
    csvFile = open(FILE, "a+")
    content = generateContent()
    for c in content:
        c_separated_by_comma = ','.join(c)
        print c_separated_by_comma
        csvFile.write( c_separated_by_comma + '\n')

# transforms content in xml
# create the root <persons>
root_element = ET.Element("persons")
# file loop
while True:
    content = csvFile.readline()
    person = ET.SubElement(root_element, "person")
    index = 0
    columns = content.split(",")
    for el in columns:
        if index == 0:
             personProperty = ET.SubElement(person, "name")
             personProperty.text = el
        elif index == 1:
             personProperty = ET.SubElement(person, "lastname")
             personProperty.text = el
        elif index == 2:
             personProperty = ET.SubElement(person, "age")
             personProperty.text = el
        elif index == 3:
             personProperty = ET.SubElement(person, "state")
             personProperty.text = el
       
        index += 1

    root_element.append( person )
    
    if content == "":
        break

#Let's see the results
# write to file:
tree = ET.ElementTree(root_element)
tree.write(XML_FILE)
csvFile.close()
